/**
 * @fileOverview
 * Paginate Blogger Posts.
 * 
 * This file is the closure version of the orignal source code.
 * It is under the licence "Apache License 2.0".
 * @author Tzu-yang Tsai, shiyou0130011@shiyou.twbbs.org
 * @version 1.01.1.20120626_β
 */

/**
 * @function
 * Setting up the pagination of blogger posts
 * @param {int} [posts_displayed=10] the number of posts displayed on each page.
 * @param {function} display_function the function display the pages. The function has 3 arguments. They are "the current page number", "the array of the links of each page", and "the number of pages". The default value is the inner function defaultDisplayFunction
 */
(function(posts_displayed, display_function){
posts_displayed = posts_displayed || 10;

/**
 * The default function of displaying pagination.
 */
var defaultDisplayFunction = function(pagenum, pagearray, numofpages){
	var page_div = document.getElementById("blog-pager"),
		styles = {
			each_items : " height: 18px; display:inline-block; border-radius: 5px; margin: 5px; font-family: cursive, 'comic sans'; font-size: 14px; padding: 2.5px;",
			special_btn : "font-weight: bolder; min-width : 36px; background-color: rgba(204, 201, 255, .75);",
			current_page : "width: 18px;background-color: rgb(67, 43, 76); color: rgb(228, 181, 255); ",
			page_link_block : "width: 18px; background-color: rgb(204, 201, 255);",
			page_link : "color: rgb(42, 8, 63)"
		};
		
	var Maximum_dispalyed = 7;
	
	function display_page_blocks(item, i, arr){
		var index = i+1;
		if(pagenum == index){
			//current page
			page_div.innerHTML += "<div class=\"current-page\" style=\"" + 
					styles.each_items + styles.current_page+
				"\">" + index + "</div>";
		}else{
			page_div.innerHTML += "<div class=\"page-num\" style=\"" + 
					styles.each_items + styles.page_link_block +
				"\">" + 
					"<a href = \""+item+"\" style=\"" + styles.page_link + "\">" +
						index + 
					"</a>" +
				"</div>";
		}
	}
	
	
	page_div.innerHTML = "";
	if(pagenum != 1){
		page_div.innerHTML += "<div class=\"first-page\" style=\"" + 
				styles.each_items + styles.special_btn +
			"\">" + 
				"<a href = \""+pagearray[0]+"\" style=\"" + styles.page_link + "\">" +
					"First Page" + 
				"</a>" +
			"</div>";
	}
	
	
	if(numofpages > Maximum_dispalyed){	//let it only display 7 pages.
		if(pagenum <= Maximum_dispalyed * 2 / 3){
			for(var i = 0; i < Maximum_dispalyed; i++){
				display_page_blocks(pagearray[i], i, pagearray);
			}
		}else if(pagenum > numofpages - Maximum_dispalyed * 2 / 3){
			for(var i = 0; i < Maximum_dispalyed; i++){
				display_page_blocks(pagearray[i + numofpages - Maximum_dispalyed], i + numofpages - Maximum_dispalyed, pagearray);
			}
		}else{
			for(var i = pagenum - 3; i < pagenum + 2; i++){
				display_page_blocks(pagearray[i], i, pagearray);
			}
		}
	}else{
		pagearray.forEach(function(item, i, arr){
			display_page_blocks(item, i, arr);
		})
	}

	if(pagenum != numofpages){
		page_div.innerHTML += "<div class=\"last-page\" style=\"" + 
				styles.each_items + styles.special_btn +
			"\">" + 
				"<a href = \""+pagearray[numofpages - 1]+"\" style=\"" + styles.page_link + "\">" +
					"Last Page" + 
				"</a>" +
			"</div>";
	}
};
if(typeof display_function != "function")
	display_function = defaultDisplayFunction;

/** The callback function of AJAX loading. */
function setFeed(feed){
	if(typeof feed == "string")
		feed = JSON.parse(feed);
	if(typeof feed != "object")
		return;
	var posts = feed.feed.entry;
	var numOfPages = parseInt(posts.length / posts_displayed);
	/*
	 * Check the page num of the current page.
	 */
	var currentPage = undefined;
	var thisPageFirstPostID = document.getElementsByClassName("date-posts")[0].getElementsByClassName("post")[0].getElementsByTagName("a")[0]["name"];
	if(!thisPageFirstPostID) return;
	
	
	
	for(var i = 0; i < posts.length; i++){
		var postID = posts[i].id.$t;
		postID = postID.split("-").pop();
		
		if(thisPageFirstPostID == postID){
			currentPage = parseInt(i / posts_displayed);
			break;
		}
	}
	
	
	var urls=[];
	for(i = 0; i < posts.length; i+= posts_displayed){
		var timestemp = posts[i]["published"]["$t"];
		timestemp = timestemp.substr(0, timestemp.indexOf(".")) + timestemp.substr(timestemp.indexOf("+"));
		timestemp = encodeURIComponent(timestemp);
		
		var pageurl = location.pathname;
		if((pageurl == "/"  || (pageurl == "/search" && location.href.indexOf("q=") < 0))   && i < posts_displayed){
			//it is the first page without any searching or tag viewing
			pageurl = "/";
			urls.push(pageurl);
			continue;
		}else if(pageurl == "/"){
			pageurl = "/search";
		}
		pageurl+= "?updated-max=" + timestemp + "&max-results=" + posts_displayed + "&by-date=true";
		
		if(location.href.indexOf("q=") > 0){
			var searchQuery, qindex = location.search.indexOf("q=") + 2;
			if(location.search.indexOf("&") >= 0)
				searchQuery = location.search.substring(qindex, location.search.indexOf("&", qindex));
			else
				searchQuery = location.search.substring(qindex);
			pageurl += "&q=" + searchQuery;
		}
		
		
		urls.push(pageurl);
	}
	display_function(currentPage+1, urls, urls.length);
	
	//setting url if it support html5 history functions
	if(history.replaceState && history.pushState && currentPage!=0){
		var newUrl;
		if(location.href.indexOf("/label/") > 0)
			newUrl = location.pathname + "/#!/Page=" + (currentPage+1);
		else if(location.href.indexOf("q=") > 0){
			var searchQuery;
			var qindex = location.search.indexOf("q=") + 2;
			if(location.search.indexOf("&") >= 0)
				searchQuery = location.search.substring(qindex, location.search.indexOf("&", qindex));
			else
				searchQuery = location.search.substring(qindex);
			
			newUrl = "./#!/q=" + searchQuery + "&Page=" + (currentPage+1);
			
			/*
			if(location.search.indexOf("by-date") >= 0){
				var byDateIndex = location.search.indexOf("by-date");
				var byDateQuery = location.search.substring(qindex, location.search.indexOf("&", byDateIndex));
				byDateQuery = byDateQuery.substring(byDateQuery.indexOf("=")+1);
				newUrl += "&sort-by-date="+byDateQuery
			}
			*/
		}else{
			newUrl = "./#!/Page=" + (currentPage+1)
		}
		history.pushState("", document.title + " Page " + currentPage, newUrl)
		history.replaceState("", document.title + " Page " + currentPage, newUrl)
	}
}
if(location.pathname.indexOf("/p/") >=0 || location.pathname.indexOf(".html")>=0){
	//if it is a page or post, do nothing.
	return;
}


var url = "/feeds/posts/summary?alt=json&max-results=2147483647";
if(location.pathname.indexOf("label") >= 0){
	var label = location.pathname.split("/").pop();
	url += "&category=" + decodeURIComponent(label);
	posts_displayed = 20;
}
if(location.search.indexOf("q=") >= 0){
	var qindex = location.search.indexOf("q=") + 2;
	var searchQuery;
	if(location.search.indexOf("&") >= 0)
		searchQuery = location.search.substring(qindex, location.search.indexOf("&", qindex));
	else
		searchQuery = location.search.substring(qindex);
	
	url += "&q=" + searchQuery;
	
	if(location.search.indexOf("by-date") >= 0){
		var byDateIndex = location.search.indexOf("by-date");
		var byDateQuery = location.search.substring(qindex, location.search.indexOf("&", byDateIndex));
		byDateQuery = byDateQuery.substring(byDateQuery.indexOf("=")+1);
		if(byDateQuery == "false")
			return;//since it is sorted by correlation. It cannot use pagenation.
	}
	url+="&by-date=true"
	posts_displayed = 20;
}



var xmlhttp = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function(){
	if (xmlhttp.readyState==4 && xmlhttp.status==200){
		//load successful
		setFeed(JSON.parse(xmlhttp.responseText));
	}
}
xmlhttp.open("GET", url,true);
xmlhttp.send();


})(5)
